<template>
  <div>
    <van-row type="flex" justify="center" style="margin-top:80px" v-if="loading">
      <van-loading type="spinner" size="24px">加载中...</van-loading>
    </van-row>
    <van-cell title="任务 ID">{{taskId}}</van-cell>
    <van-cell title="类型" value="机务作业" />
    <van-cell title="机车号">{{ trainPlanInfo.trainNo }}</van-cell>
    <van-cell title="车次号">{{ trainPlanInfo.trainNumber }}</van-cell>
    <van-cell title="状态">
      <van-tag v-if="this.taskInfo.state === 1">待审核</van-tag>
      <van-tag type="warning" v-else-if="this.taskInfo.state === 2">审核中</van-tag>
      <van-tag type="primary" v-else-if="this.taskInfo.state === 3">已批准</van-tag>
      <van-tag type="danger" v-else-if="this.taskInfo.state === 4">已拒绝</van-tag>
      <van-tag type="success" v-else-if="this.taskInfo.state === 5">进行中</van-tag>
      <van-tag v-else-if="this.taskInfo.state === 6">已完成</van-tag>
      <van-tag v-else-if="this.taskInfo.state === 7">已销毁</van-tag>
      <van-tag v-else>未知</van-tag>
    </van-cell>

    <!-- <van-cell title="创建人" value="张三" />
    <van-cell title="创建时间" value="2022-07-25 09:06:31" />-->
    <van-cell title="计划时间" :value="show.planedTime" />
    <van-cell title="开始时间" :value="show.beginTime" />
    <van-cell title="结束时间" :value="show.endTime" />
    <van-cell v-if="taskSetting.hasWorkArea" title="机务地点" :value="show.LJPlace" />
    <van-cell v-if="!taskSetting.hasWorkArea" title="机务地点" :value="show.areaComment" />
    <van-cell v-if="taskSetting.hasWorkArea" title="地点补充" :value="show.areaComment" />
    <van-cell title="机务内容" :value="taskInfo.workContent" />
    <van-field
      v-model="show.beginTime_plan"
      label="机务任务"
      placeholder="请选择"
      input-align="right"
      readonly
      @click="shuntPicker=true"
    />
    <van-popup v-model="shuntPicker" round position="bottom" :style="{ height: '50%' }">
      <van-dropdown-menu>
        <van-dropdown-item v-model="ShuntWorkPicker.select" :options="ShuntWorkPicker.options" />
      </van-dropdown-menu>
      <van-cell :key="flashnumber">
        <span
          v-if="this.ShuntWorkStateMap[this.ShuntWorkPicker.select]%10 === 0"
          style="display:block; margin-top:25%; margin-left: 38%;"
        >
          <van-tag
            type="success"
            @click="onClickStartTask(ShuntWorkPicker.select, ShuntWorkStateMap[ShuntWorkPicker.select])"
          >开始任务</van-tag>
        </span>
        <span
          v-else-if="this.ShuntWorkStateMap[this.ShuntWorkPicker.select]%10 === 1"
          style="display:block; margin-top:25%; margin-left: 38%;"
        >
          <!-- <van-tag type="warning" style="margin-right:32px">人工预警</van-tag> -->
          <van-tag
            type="danger"
            @click="onClickStartTask(ShuntWorkPicker.select, ShuntWorkStateMap[ShuntWorkPicker.select])"
          >结束任务</van-tag>
        </span>
        <span
          v-else-if="this.ShuntWorkStateMap[this.ShuntWorkPicker.select]%10 === 2"
          style="display:block; margin-top:25%; margin-left: 38%;"
        >
          <!-- <van-tag type="warning" style="margin-right:32px">人工预警</van-tag> -->
          <van-tag type="danger">已结束</van-tag>
        </span>
      </van-cell>
    </van-popup>
    <van-cell title="我的角色" :value="show.role" />
    <van-cell title="负责人" :value="show.manager" @click="onClickRole('manager')" />
    <van-cell title="机务员" :value="show.trainChecker" @click="onClickRole('trainChecker')" />
    <van-cell title="备注" :value="taskInfo.comment" />
    <!-- <van-cell title="修改" v-if="this.taskInfo.state === 3">
      <span v-if="this.taskInfo.state === 3">
        <van-tag type="success" @click="onClickUpdateTask">修改任务</van-tag>
      </span>
    </van-cell>-->
    <van-cell title="照片/视频" />
    <van-uploader v-model="picFileList" multiple :after-read="afterRead" :deletable="false" />
    <van-dialog v-model="showDetailDialog" :title="dialogTitle">
      <div class="roleDetail">
        <van-cell>
          <van-row>
            <van-col span="4">
              <span class="table-head">ID</span>
            </van-col>
            <van-col span="5">
              <span class="table-head">类型</span>
            </van-col>
            <van-col span="6">
              <span class="table-head">名称</span>
            </van-col>
            <van-col span="9">
              <span class="table-head">组织</span>
            </van-col>
          </van-row>
        </van-cell>
        <van-cell v-for="(item, index) in dialogData" :key="index">
          <van-row>
            <van-col span="4">
              <span class="table-content">{{getRoleDetailID(item)}}</span>
            </van-col>
            <van-col span="5">
              <span class="table-content">{{getRoleDetailType(item)}}</span>
            </van-col>
            <van-col span="6">
              <span class="table-content">{{item.name}}</span>
            </van-col>
            <van-col span="9"></van-col>
          </van-row>
        </van-cell>
      </div>
    </van-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
// import { getFormatDate, getFormatHourMinute } from '../utils/datetime'
import {
  getPlanTimeStr,
  getBeginEndTimeStr,
  getRoleStr,
  getRoleDetailID,
  getRoleDetailType,
  getTaskInfoRoleShow,
  getLJPlaceShow,
  fillRoleData,
  getFenceIds,
  getTaskTypeStr,
  getTaskStateStr
} from '../../utils/taskUtils'
import { putDCTaskOperate } from '@/api/task'
export default {
  name: '',
  components: {},
  props: {},
  data() {
    return {
      loading: true,
      flashnumber: 1,
      trainPlanInfo: {},
      taskId: '',
      // baseURL: 'http://152.136.13.167:9527',
      baseURL: window.location.origin,
      taskInfo: {},
      shuntPicker: false,
      ShuntWorkStateMap: {},
      ShuntWorkPicker: {
        select: 0,
        option: '',
        options: []
      },
      roleData: {
        manager: [],
        trainChecker: []
      },
      roleName: {
        manager: '负责人',
        trainChecker: '列检员'
      },
      show: {
        role: '',
        planedTime: '---',
        beginTime: '---',
        endTime: '---',
        manager: '',
        trainChecker: '',
        LJPlace: '',
        fence: '',
        areaComment: '',
        workContent: ''
      },
      memberDetail: {},
      showDetailDialog: false,
      dialogTitle: '',
      dialogData: [],
      role: -1,
      picFileList: []
    }
  },
  computed: {
    ...mapGetters(['userId', 'deviceId', 'taskSetting'])
  },
  watch: {},
  created() {
    this.taskId = this.$router.currentRoute.query.taskId
    this.role = this.$router.currentRoute.query.role
    try {
      this.getTaskInfo(this.taskId)
      this.$toast('获取任务信息成功')
    } catch (err) {
      // 对异步异常无效，await的异常怎么捕获更合理待研究
      console.log(err)
      this.loading = false
      this.$toast('获取任务信息失败')
    }
    this.getPicURL()
  },
  mounted() {
    this.sockets.subscribe('TaskChangeBriefInfo', async (channelMsg) => {
      console.log('[TASKINFO_LJ] Recv Channel TaskChangeBriefInfo')
      if (this.taskId === channelMsg.data.taskId) {
        console.log(channelMsg)
        this.loading = true
        this.getTaskInfo(this.taskId)
        const notice = `当前任务：${getTaskTypeStr(channelMsg.data.type)}(id: ${channelMsg.data.taskId}) ${getTaskStateStr(channelMsg.data.state)}！`
        this.$dialog.alert({
          message: notice
        })
      }
    })
  },
  beforeDestroy() {
    this.sockets.unsubscribe('TaskChangeBriefInfo')
  },
  methods: {
    onClickUpdateTask() {
      const taskCreatePathLJ = '/taskupdate/lj'
      const taskInfo = this.taskInfo
      this.$router.push({ path: taskCreatePathLJ, query: { taskInfo, taskId: this.taskInfo.taskId } })
    },
    onClickRole(role) {
      this.dialogTitle = this.roleName[role]
      this.dialogData = this.roleData[role]
      this.showDetailDialog = true
    },
    onClickFence() {
      this.$toast('【查看围栏功能】 正在开发中...')
    },
    fillTaskShow(task) {
      this.show.planedTime = getPlanTimeStr(task.beginTime_plan, task.endTime_plan)
      if (this.taskInfo.beginTime) {
        this.show.beginTime = getBeginEndTimeStr(this.taskInfo.beginTime)
      }
      if (this.taskInfo.endTime) {
        this.show.endTime = getBeginEndTimeStr(this.taskInfo.endTime)
      }
      this.show.role = getRoleStr(parseInt(this.role))
      this.show.manager = getTaskInfoRoleShow(this.roleData.manager)
      this.show.trainChecker = getTaskInfoRoleShow(this.roleData.trainChecker)
      this.show.LJPlace = getLJPlaceShow(task.workArea)
      this.show.fence = task.fenceIds.length ? `围栏(id:${task.fenceIds.toString()})` : '无'
      this.show.areaComment = task.workArea.areaDescription ? task.workArea.areaDescription : ''
      this.show.comment = task.comment ? task.comment : ''
    },
    async getPicURL() {
      const { data } = await this.$http.get('/pic/getImagePaths', { params: { taskId: this.taskId } })
      if (data.code === 0) {
        data.data.forEach((path) => {
          this.picFileList.push({ url: `${window.location.origin}/pic/${path}` })
        })
      }
    },
    async afterRead(e) {
      // 此时可以自行将文件上传至服务器
      e.status = 'uploading'
      e.message = '上传中...'
      const fd = new FormData()
      fd.append('deviceId', this.deviceId)
      if (this.userId) {
        fd.append('userId', this.deviceId)
      }
      fd.append('taskId', this.taskId)
      fd.append('file', e.file)
      await this.$http({
        method: 'post',
        url: '/pic/upload',
        data: fd
      })
      e.status = 'done'
    },
    async getTaskInfo(taskId) {
      var data2 = await this.$http.get('/task/planWorkTaskInfo', { params: { taskId } })
      data2 = data2.data
      this.trainPlanInfo = data2.data
      if (data2.code === 0) {
        const data3 = await this.$http.get('/task/DCtaskInfo', { params: { trainID: data2.data.trainId, receiveMark: data2.data.receiveMark } })
        if (data3.data.code === 0) {
          for (var key in JSON.parse(data3.data.data.DCWorkList)) {
            if (JSON.parse(data3.data.data.DCWorkList)[key] >= 10) {
              this.ShuntWorkPicker.options.push({ text: key, value: key })
              this.ShuntWorkStateMap[key] = JSON.parse(data3.data.data.DCWorkList)[key]
            }
          }
        }
      }
      const { data } = await this.$http.get('/task/taskInfo', { params: { taskId } })
      if (data.code === 0) {
        this.taskInfo = data.data
        this.taskInfo.fenceIds = getFenceIds(this.taskInfo.fences)
        this.roleData.manager = await fillRoleData(this.taskInfo.manager)
        this.roleData.trainChecker = await fillRoleData(this.taskInfo.trainChecker)
        this.fillTaskShow(this.taskInfo)
        this.loading = false
        console.log(this.taskInfo)
      }
    },
    async onClickStartTask(taskType, taskState) {
      console.log(taskType)
      console.log(taskState)
      var respon = await this.$http.put('/task/operateDC', {
        params: { taskId: this.$route.query.taskId, taskType, taskState, trainID: this.trainPlanInfo.trainId, receiveMark: this.trainPlanInfo.receiveMark }
      })
      respon = respon.data
      if (respon.code === 0) {
        for (var key in respon.data.DCtaskList) {
          if (this.ShuntWorkStateMap[key] || this.ShuntWorkStateMap[key] === 0) {
            this.ShuntWorkStateMap[key] = respon.data.DCtaskList[key]
          }
        }
        console.log(this.ShuntWorkStateMap)
        if (this.flashnumber === 1) {
          this.flashnumber = 0
        } else {
          this.flashnumber = 1
        }
      }
    },
    async onClickEndTask() {
      const respon = await putDCTaskOperate(this.taskId, 'endTask')
      if (respon.code === 0) {
        this.taskInfo.state = respon.data.state
        this.taskInfo.endTime = respon.data.endTime
        if (this.taskInfo.endTime) {
          this.show.endTime = getBeginEndTimeStr(this.taskInfo.endTime)
        }
      }
    },
    getRoleDetailID(item) {
      return getRoleDetailID(item)
    },
    getRoleDetailType(item) {
      return getRoleDetailType(item)
    }
  }
}
</script>

<style lang="less" scoped>
.van-cell {
  .van-cell__value {
    min-width: 70%;
  }
}

.roleDetail {
  margin: 20px;
  .table-head {
    font-weight: 700;
    font-size: 30px;
  }
  .table-content {
    font-size: 30px;
  }
  .van-cell {
    padding: 0 20px;
  }
}

.loading {
  margin: 50px;
}
</style>
